<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: yatego.php 11 2013-09-21 11:43:11Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 11 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-21 11:43:11 +0000 (Sat, 21 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

defined( '_VALID_XTC' ) or die( 'Direct Access to this location is not allowed.');

define('MODULE_YATEGO_TEXT_DESCRIPTION', 'Export - yatego (; getrennt)<br><b>Format:</b><br>foreign_id	article_nr	title	tax	price	price_uvp	basic_price	units	delivery_surcharge	short_desc	long_desc	url	auto_linefeet	picture	picture2	picture3	picture4	picture5	categories	variants	stock	cross_selling	delitem');
define('MODULE_YATEGO_TEXT_TITLE', 'yatego - CSV');
define('MODULE_YATEGO_FILE_TITLE' , '<hr noshade>Dateiname');
define('MODULE_YATEGO_FILE_DESC' , 'Geben Sie einen Dateinamen ein, falls die Exportadatei am Server gespeichert werden soll.<br>(Verzeichnis export/)');
define('MODULE_YATEGO_STATUS_DESC','Modulstatus');
define('MODULE_YATEGO_STATUS_TITLE','Status');
define('MODULE_YATEGO_CURRENCY_TITLE','WР Т‘hrung');
define('MODULE_YATEGO_CURRENCY_DESC','Welche Währung soll exportiert werden?');
define('EXPORT_YES','Nur Herunterladen');
define('EXPORT_NO','Am Server Speichern');
define('CURRENCY','<hr noshade><b>W&auml;hrung:</b>');
define('CURRENCY_DESC','WР Т‘hrung in der Exportdatei');
define('EXPORT','Bitte den Sicherungsprozess AUF KEINEN FALL unterbrechen. Dieser kann einige Minuten in Anspruch nehmen.');
define('EXPORT_TYPE','<hr noshade><b>Speicherart:</b>');
define('EXPORT_STATUS_TYPE','<hr noshade><b>Kundengruppe:</b>');
define('EXPORT_STATUS','Bitte w&auml;hlen Sie die Kundengruppe, die Basis f&uuml;r den Exportierten Preis bildet. (Falls Sie keine Kundengruppenpreise haben, w&auml;hlen Sie <i>Gast</i>):</b>');

require_once(DIR_FS_INC."inc.get_parent_categories.php");
require_once(DIR_FS_INC."inc.get_product_path.php");

class Yatego {
    var $code, $title, $description, $enabled, $db;

    function __construct() {
      global $order, $db;

      $this->code = 'yatego';
	  $this->img = 'images/export/yatego.gif';
      $this->title = MODULE_YATEGO_TEXT_TITLE;
      $this->description = MODULE_YATEGO_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_YATEGO_SORT_ORDER;
      $this->enabled = ((MODULE_YATEGO_STATUS == 'True') ? true : false);
      $this->db = $db;

    }

	function _get_shipping_costs($weight) {
        return "";
 	}

    function process($file) {

        @set_time_limit(0);
        error_reporting(0);
        include_once(DIR_FS_CATALOG.DIR_WS_CLASSES . 'class.price.php');
        $price = new price($_POST['currencies'],$_POST['status'], $this->db);

        $schema = "foreign_id;article_nr;title;tax;price;price_uvp;basic_price;units;delivery_surcharge;short_desc;long_desc;url;auto_linefeet;picture;picture2;picture3;picture4;picture5;categories;variants;stock;cross_selling;delitem;status\n";
		$products = $this->db->db_query("SELECT
				                             p.products_id,
				                             pd.products_name,
				                             pd.products_description,
				                             p.products_model,
				                             p.products_weight,
				                             p.products_image,
				                             p.products_price,
				                             p.products_status,
				                             p.products_shippingtime,
				                             p.products_discount_allowed,
				                             p.products_tax_class_id,
											 p.products_ean,
				                             p.products_date_added,
				                             m.brand_name
				                         FROM
				                             " . TABLE_PRODUCTS . " p LEFT JOIN
				                             " . TABLE_BRAND . " m
				                           ON p.brand_id = m.brand_id LEFT JOIN
				                             " . TABLE_PRODUCTS_DESCRIPTION . " pd
				                           ON p.products_id = pd.products_id AND
				                            pd.language_id = '".$_SESSION['languages_id']."' LEFT JOIN
				                             " . TABLE_SPECIALS . " s
				                           ON p.products_id = s.products_id
				                         WHERE
				                           p.products_status = 1
				                         ORDER BY
				                            p.products_date_added DESC,
				                            pd.products_name");


        while(!$products->EOF) {
            $products_price = $price->GetPrice($products->fields['products_id'], false, 1, $products->fields['products_tax_class_id']);

            // remove trash
            $products_description = strip_tags($products->fields['products_description']);
            $products_description = substr($products_description, 0, 3500) . '..';
            $products_description = str_replace(";",", ",$products_description);
            $products_description = str_replace("'",", ",$products_description);
            $products_description = str_replace("\n"," ",$products_description);
            $products_description = str_replace("\r"," ",$products_description);
            $products_description = str_replace("\t"," ",$products_description);
            $products_description = str_replace("\v"," ",$products_description);
            $products_description = str_replace("&quot,"," \"",$products_description);
            $products_description = str_replace("&qout,"," \"",$products_description);

			//GР В¦: resolve categorie array name
			$cat_array = $this->goe_get_products_categories_path($products->fields['products_id']);
			$cat_string = implode(" / ",$cat_array);

  			$sep = ";";
  			$ProduktID        = $products->fields['products_id'];
			$Hersteller       = html_entity_decode($products->fields['brand_name']);
			$Produktname      = html_entity_decode($products->fields['products_name']);
			$Produktname      = substr($Produktname, 0, 50);
			$HerstellerID     = "";
			$EAN			  = $products->fields['products_ean'];
			$Preis            = number_format((float)$products_price,2,",","");
			$Versandkosten    = $this->_get_shipping_costs($products->fields['weight']);
			$Versandkosten    = number_format((float)$Versandkosten,2,",","");
			$Deeplink         = HTTP_CATALOG_SERVER . DIR_WS_CATALOG . 'product_info.php?products_id=' . $products->fields['products_id'] . "&c1=Preissuchmaschine&source=yatego&kw=" . $products_price;
			$Kategorie        = html_entity_decode($cat_string);
			$Beschreibung     = html_entity_decode($products_description);
			$Kurzbeschreibung = substr(html_entity_decode($products_description), 0, 120) . '..';

			$HaendlerArtNr    = $products->fields['products_model'];
			$Lieferzeit       = get_shipping_status_name($products->fields['products_shippingtime']);
			$ImageURL         = HTTP_CATALOG_SERVER . DIR_WS_CATALOG_THUMBNAIL_IMAGES .$products->fields['products_image'];

			$current = 			$ProduktID . $sep .
								$ProduktID . $sep .
								$Produktname . $sep .
								"19" . $sep .
								$Preis . $sep .
								" " . $sep .
								"0" . $sep .
								"1" . $sep .
								$Versandkosten . $sep .
								$Kurzbeschreibung . $sep .
								$Beschreibung . $sep .
								$Deeplink . $sep .
								"1" . $sep .
								$ImageURL . $sep .
								"" . $sep .
								"" . $sep .
								"" . $sep .
								"" . $sep .
								"" . $sep .
								"" . $sep .
								"-1" . $sep .
								"" . $sep .
								"" . $sep .
								"1" . "\n";
           $schema .= $current;
			$products->MoveNext();
        }

		// create File
        $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/' . $file, "w+");
        fputs($fp, $schema);
        fclose($fp);

        unset($price);

      switch ($_POST['export']) {
        case 'yes':
            // send File to Browser
            $extension = substr($file, -3);
            $fp = fopen(DIR_FS_DOCUMENT_ROOT.'export/' . $file,"rb");
            $buffer = fread($fp, filesize(DIR_FS_DOCUMENT_ROOT.'export/' . $file));
            fclose($fp);

            header('Content-type: application/x-octet-stream');
            header('Content-disposition: attachment; filename=' . $file);
            echo $buffer;
            exit;
        break;
        }

    }

	function goe_get_products_categories_path($products_id) {
       $categorie_data = get_product_path($products_id);
	   $foo = explode("_",$categorie_data);

	   $cat_name = array();

		foreach($foo as $cid) {
		      $categories = $this->db->db_query("SELECT
													cd.categories_name
												FROM
													" . TABLE_CATEGORIES_DESCRIPTION . " cd,
													".TABLE_CATEGORIES." c
												WHERE
													cd.categories_id = '" . $cid . "'
												AND
													c.categories_id = cd.categories_id ".$group_check."
												AND
													cd.language_id='2'");

			if($categories->_numOfRows > 0)
				$cat_name[] = $categories->fields['categories_name'];
		}
	   	return $cat_name;
    }


    function display() {

	    $customers_statuses_array = get_customers_statuses();

	    $curr='';
	    $currencies = $this->db->db_query("SELECT code FROM ".TABLE_CURRENCIES);
	    while(!$currencies->EOF) {
	    	$curr.=draw_radio_field('currencies', $currencies_data->fields['code'],true).$currencies_data->fields['code'].'<br />';
	    	$currencies->MoveNext();
	    }

	    return array('text' =>  EXPORT_STATUS_TYPE.'<br>'.
	                          	EXPORT_STATUS.'<br>'.
	                          	draw_pull_down_menu('status',$customers_statuses_array, '1').'<br>'.
	                            CURRENCY.'<br>'.
	                            CURRENCY_DESC.'<br>'.
	                            $curr.
	                            EXPORT_TYPE.'<br>'.
	                            EXPORT.'<br>'.
	                          	draw_radio_field('export', 'no',true).EXPORT_NO.'<br>'.

		draw_radio_field('export', 'yes',false).EXPORT_YES.'<br>'.
							'<br>' . button(BUTTON_EXPORT) .
							button_link(BUTTON_CANCEL, href_link(FILENAME_MODULE_EXPORT,
							'set=' . $_GET['set'] . '&module=Yatego')));
	}

	function check() {
		if (!isset($this->_check)) {
			$check = $this->db->db_query("SELECT configuration_value from " . TABLE_CONFIGURATION . " WHERE configuration_key = 'MODULE_YATEGO_STATUS'");
			$this->_check = $check->_numOfRows;
		}
		return $this->_check;
    }

    function install() {
		$this->db->db_query("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_YATEGO_FILE', 'yatego.csv',  '6', '1', '', now())");
		$this->db->db_query("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) VALUES ('MODULE_YATEGO_STATUS', 'True',  '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
	}

    function remove() {
		$this->db->db_query("DELETE FROM " . TABLE_CONFIGURATION . " WHERE configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
		return array('MODULE_YATEGO_STATUS','MODULE_YATEGO_FILE');
    }
}
?>
